import axios from 'axios'
import { Course, CourseFilter, CourseProgress, CourseReview, Chapter, Lesson } from '../types/course'

export const courseService = {
  async getCourses(filter?: CourseFilter) {
    try {
      const response = await axios.get('/api/courses', { params: filter })
      return response.data as Course[]
    } catch (error) {
      throw new Error('获取课程列表失败')
    }
  },

  async getCourseDetail(courseId: string) {
    try {
      const response = await axios.get(`/api/courses/${courseId}`)
      return response.data as Course
    } catch (error) {
      throw new Error('获取课程详情失败')
    }
  },

  async getCourseChapters(courseId: string) {
    try {
      const response = await axios.get(`/api/courses/${courseId}/chapters`)
      return response.data as Chapter[]
    } catch (error) {
      throw new Error('获取课程章节失败')
    }
  },

  async getCourseLessons(chapterId: string) {
    try {
      const response = await axios.get(`/api/chapters/${chapterId}/lessons`)
      return response.data as Lesson[]
    } catch (error) {
      throw new Error('获取课时列表失败')
    }
  },

  async enrollCourse(courseId: string) {
    try {
      const response = await axios.post(`/api/courses/${courseId}/enroll`)
      return response.data
    } catch (error) {
      throw new Error('课程报名失败')
    }
  },

  async getCourseProgress(courseId: string) {
    try {
      const response = await axios.get(`/api/courses/${courseId}/progress`)
      return response.data as CourseProgress
    } catch (error) {
      throw new Error('获取课程进度失败')
    }
  },

  async updateCourseProgress(courseId: string, lessonId: string) {
    try {
      const response = await axios.post(`/api/courses/${courseId}/progress`, { lessonId })
      return response.data as CourseProgress
    } catch (error) {
      throw new Error('更新课程进度失败')
    }
  },

  async getCourseReviews(courseId: string) {
    try {
      const response = await axios.get(`/api/courses/${courseId}/reviews`)
      return response.data as CourseReview[]
    } catch (error) {
      throw new Error('获取课程评价失败')
    }
  },

  async addCourseReview(courseId: string, reviewData: { rating: number; comment: string }) {
    try {
      const response = await axios.post(`/api/courses/${courseId}/reviews`, reviewData)
      return response.data as CourseReview
    } catch (error) {
      throw new Error('添加课程评价失败')
    }
  }
}
